package com.manolo.framework.connection.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import com.manolo.framework.connection.entity.Message;
import com.manolo.framework.connection.entity.Player;

public class ServerPlayer implements Runnable {

	private Integer playerId;

	private Socket client;

	private HashMap<Integer, Player> players;

	private BufferedReader in;

	public ServerPlayer(Integer playerId, Socket client,
			HashMap<Integer, Player> players) {
		super();
		this.client = client;
		this.players = players;
		this.playerId = playerId;
	}

	private boolean createConnection() {

		boolean isConnected = false;

		try {
			players.put(playerId, new Player());

			// Send message to another player that new player join to game
			sendMsgNewPlayer();

			// Create the players that already exists
			sendCreatePlayers();

			Thread listerThread = new Thread(new ServerPlayerLister(playerId,
					client, players));
			listerThread.setName("Listener::"+ listerThread.getName());

			Thread sendThread = new Thread(new ServerPlayerSender(playerId,
					client, players));
			
			sendThread.setName("Sender::"+ sendThread.getName());
			
			listerThread.start();
			sendThread.start();
			isConnected = true;

		} catch (IOException e) {
			System.out.println("Error to create connection to client");
			System.exit(-1);
		}

		return isConnected;
	}

	public void sendMsgNewPlayer() throws IOException {

		Message msgt = new Message();
		msgt.setName("ServerCreateNewPlayer");
		msgt.setContent("Hello Player " + playerId + " Join to game");
		msgt.setId(playerId);

		// players.get(playerId).getMessages().add(msgt);

		Set<Integer> keys = players.keySet();
		for (Integer id : keys) {
			if (id != playerId) {
				players.get(id).getMessages().add(msgt);
			}
		}

	}

	public void sendCreatePlayers() throws IOException {

		if (playerId > 0) {
			for (int identification = 0; identification < playerId; identification++) {
				Message msgt = new Message();
				msgt.setName("ServerCreateNewPlayer");
				msgt.setContent("Player " + identification + " Join to game");
				msgt.setId(identification);
				players.get(playerId).getMessages().add(msgt);
			}
		}
	}

	@Override
	public void run() {
		// create connection
		boolean isConnected = createConnection();


	}

}
